#!/usr/bin/env python3
"""
前端UI功能测试脚本
测试前端是否能正确处理后端的UI指令并更新界面
"""

import requests
import json
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def test_frontend_ui_response():
    """测试前端UI响应功能"""
    
    print("🧪 开始前端UI响应测试...")
    
    # Chrome选项
    chrome_options = Options()
    chrome_options.add_argument("--headless")  # 无头模式
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")
    
    driver = None
    try:
        driver = webdriver.Chrome(options=chrome_options)
        
        # 访问前端页面
        print("🌐 打开前端页面...")
        driver.get("http://localhost:8089/living_workspace.html")
        
        # 等待页面加载
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "chatInput"))
        )
        print("✅ 页面加载完成")
        
        # 测试1: 筛选Python工程师
        print("\n🔍 测试1: 筛选Python工程师功能")
        
        # 输入消息
        chat_input = driver.find_element(By.ID, "chatInput")
        chat_input.clear()
        chat_input.send_keys("筛选会Python的工程师，显示前3个")
        
        # 点击发送按钮
        send_btn = driver.find_element(By.ID, "sendBtn")
        send_btn.click()
        
        # 等待响应
        print("⏳ 等待AI响应...")
        time.sleep(8)  # 等待AI响应
        
        # 检查是否有候选人卡片出现
        try:
            candidate_cards = driver.find_elements(By.CLASS_NAME, "candidate-card")
            if len(candidate_cards) > 0:
                print(f"✅ 测试1通过: 找到 {len(candidate_cards)} 个候选人卡片")
                
                # 检查候选人信息
                for i, card in enumerate(candidate_cards[:3]):
                    try:
                        name = card.find_element(By.CLASS_NAME, "candidate-name").text
                        skills = card.find_element(By.CLASS_NAME, "candidate-skills").text
                        print(f"   候选人{i+1}: {name} - 技能: {skills}")
                    except:
                        print(f"   候选人{i+1}: 信息读取失败")
            else:
                print("❌ 测试1失败: 没有找到候选人卡片")
                return False
        except Exception as e:
            print(f"❌ 测试1失败: {e}")
            return False
        
        # 测试2: 生成面试题
        print("\n📝 测试2: 生成面试题功能")
        
        # 输入面试题生成请求
        chat_input.clear()
        chat_input.send_keys("给候选人10751444出一道面试题")
        send_btn.click()
        
        # 等待响应
        print("⏳ 等待面试题生成...")
        time.sleep(6)
        
        # 检查是否出现面试题模态框
        try:
            modals = driver.find_elements(By.CLASS_NAME, "interview-modal")
            if len(modals) > 0 and modals[0].is_displayed():
                print("✅ 测试2通过: 面试题模态框显示成功")
                
                # 检查面试题内容
                questions = driver.find_elements(By.CLASS_NAME, "question-item")
                print(f"   面试题数量: {len(questions)}")
                
                for i, question in enumerate(questions[:2]):
                    try:
                        question_text = question.find_element(By.TAG_NAME, "p").text
                        print(f"   问题{i+1}: {question_text[:50]}...")
                    except:
                        print(f"   问题{i+1}: 内容读取失败")
            else:
                print("❌ 测试2失败: 面试题模态框没有显示")
                return False
        except Exception as e:
            print(f"❌ 测试2失败: {e}")
            return False
        
        print("\n🎉 所有前端UI测试通过！")
        return True
        
    except Exception as e:
        print(f"💥 测试过程中发生异常: {e}")
        return False
    finally:
        if driver:
            driver.quit()

def test_backend_response():
    """测试后端响应数据结构"""
    print("\n🔧 测试后端响应数据结构...")
    
    try:
        # 测试筛选请求
        response = requests.post(
            "http://localhost:8089/api/chat",
            json={"message": "筛选会Python的工程师，显示前2个"},
            timeout=10
        )
        
        if response.status_code == 200:
            data = response.json()
            
            # 检查UI指令
            ui_commands = data.get('ui_commands', [])
            analyzed_candidates = data.get('analyzed_candidates', [])
            
            print(f"✅ UI指令数量: {len(ui_commands)}")
            print(f"✅ 候选人数量: {len(analyzed_candidates)}")
            
            if ui_commands:
                print(f"✅ 第一个UI指令: {ui_commands[0].get('command', 'None')}")
            
            return len(ui_commands) > 0 and len(analyzed_candidates) > 0
        else:
            print(f"❌ HTTP错误: {response.status_code}")
            return False
            
    except Exception as e:
        print(f"❌ 后端测试失败: {e}")
        return False

if __name__ == "__main__":
    print("🚀 开始HR系统前端UI功能验证")
    print("=" * 60)
    
    # 先测试后端
    backend_ok = test_backend_response()
    if not backend_ok:
        print("❌ 后端测试失败，跳过前端测试")
        exit(1)
    
    # 再测试前端
    frontend_ok = test_frontend_ui_response()
    
    if backend_ok and frontend_ok:
        print("\n🎉 完整的前后端UI功能测试通过！")
        exit(0)
    else:
        print("\n❌ 测试失败")
        exit(1)





